package com.example.myapplicationwork.network;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 网络请求工具类
 * 使用HttpURLConnection实现网络请求
 */
public class NetworkUtils {
    private static final String TAG = "NetworkUtils";
    private static final int TIMEOUT = 10000; // 10秒超时

    /**
     * 发送POST请求
     * @param url 请求URL
     * @param jsonData 请求体JSON数据
     * @return 响应结果
     */
    public static String postRequest(String url, String jsonData) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");

            // 发送请求体
            if (jsonData != null && !jsonData.isEmpty()) {
                outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes(jsonData);
                outputStream.flush();
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                InputStream inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } else {
                Log.e(TAG, "POST请求失败: 响应码 " + responseCode);
                // 请求失败时直接返回null，不读取错误流
                return null;
            }

        } catch (IOException e) {
            Log.e(TAG, "POST请求异常", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                Log.e(TAG, "关闭资源异常", e);
            }
        }

        return response.toString();
    }

    /**
     * 发送GET请求
     * @param url 请求URL
     * @return 响应结果
     */
    public static String getRequest(String url) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            connection.setRequestProperty("Accept", "application/json");

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } else {
                Log.e(TAG, "GET请求失败: 响应码 " + responseCode);
                // 请求失败时直接返回null，不读取错误流
                return null;
            }

        } catch (IOException e) {
            Log.e(TAG, "GET请求异常", e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                Log.e(TAG, "关闭资源异常", e);
            }
        }

        return response.toString();
    }
}